import wx
from LMG.Utility.helpers import LimitedNumCtrl

class WebDialog(wx.Dialog):
    """
    Let the user specify settings for the webservice
    """
    def __init__(self, parent):        
        wx.Dialog.__init__(self, parent, -1, _('Web Interface Service'))
        
        utility.webserver.webdlg = self
               
        outerbox = wx.BoxSizer(wx.VERTICAL)
        
        credentials_box = wx.StaticBoxSizer(wx.StaticBox(self, -1, _('Protocol')), wx.VERTICAL)
        credentials_grid = wx.FlexGridSizer(cols = 4, vgap = 5, hgap = 10)

        ip_choices = [_('Automatic'), _('Loop Back')]
        credentials_grid.Add(wx.StaticText(self, -1, _('IP:')), 0, wx.ALIGN_CENTER_VERTICAL)
        self.iptext = wx.ComboBox(self, -1, choices = ip_choices, style = wx.CB_DROPDOWN|wx.CB_READONLY)
        credentials_grid.Add(self.iptext, 0, wx.EXPAND|wx.ALIGN_CENTER_VERTICAL)

        credentials_grid.Add(wx.StaticText(self, -1, _('Port:')), 0, wx.ALIGN_CENTER_VERTICAL)
        self.porttext = LimitedNumCtrl(self, max = 65536)
        credentials_grid.Add(self.porttext, 0, wx.EXPAND|wx.ALIGN_CENTER_VERTICAL)

        credentials_grid.Add(wx.StaticText(self, -1, _('Username:')), 0, wx.ALIGN_CENTER_VERTICAL)        
        self.username = wx.TextCtrl(self, -1, "")
        self.username.SetToolTipString(_('Enter the username you wish to use to access the web service'))
        credentials_grid.Add(self.username, 1, wx.EXPAND|wx.ALIGN_CENTER_VERTICAL)
        
        credentials_grid.Add(wx.StaticText(self, -1, _('Password:')), 0, wx.ALIGN_CENTER_VERTICAL)
        self.password = wx.TextCtrl(self, -1, "", style = wx.TE_PASSWORD)
        self.password.SetToolTipString(_('Enter the password you wish to use to access the web service'))
        credentials_grid.Add(self.password, 1, wx.EXPAND|wx.ALIGN_CENTER_VERTICAL)

        authorization_choices = [_('Basic'), _('Digest Access')]
        credentials_grid.Add(wx.StaticText(self, -1, _('Authorization:')), 0, wx.ALIGN_CENTER_VERTICAL)
        self.authorizationtext = wx.ComboBox(self, -1, choices = authorization_choices, style = wx.CB_DROPDOWN|wx.CB_READONLY)
        credentials_grid.Add(self.authorizationtext, 0, wx.EXPAND|wx.ALIGN_CENTER_VERTICAL)

        credentials_grid.Add(wx.StaticText(self, -1, _('Allowed IP:')), 0, wx.ALIGN_CENTER_VERTICAL)        
        self.allowed = wx.TextCtrl(self, -1, "")
        self.allowed.SetToolTipString(_('List of IP addresses allowed to access your client. Separate using commas'))
        credentials_grid.Add(self.allowed, 1, wx.EXPAND|wx.ALIGN_CENTER_VERTICAL)

        credentials_box.Add(credentials_grid, 0, wx.ALIGN_CENTER_VERTICAL)
        outerbox.Add(credentials_box, 0, wx.EXPAND|wx.ALL, 5)
                
        permissions_box = wx.StaticBoxSizer(wx.StaticBox(self, -1, _('Command Permissions')), wx.VERTICAL)
        self.permissions = [ [_('Quit'), 'allow_quit'],
                             [_('Version'), 'allow_version'], 
                             [_('Query'), 'allow_query'],
                             [_('Get files'), 'allow_getfiles'],
                             [_('Set file priorities'), 'allow_setfileprio'],
                             [_('Get settings'), 'allow_getsettings'],
                             [_('Set settings'), 'allow_setsettings'],
                             [_('Set torrent parameters'), 'allow_getprops'], 
                             [_('Get torrent parameters'), 'allow_setprops'],
                             [_('Set torrent priority'), 'allow_setpriority'],
                             [_('Add URL'), 'allow_addurl'], 
                             [_('Add File'), 'allow_addfile'], 
                             [_('Remove'), 'allow_remove'],
                             [_('Remove Files'), 'allow_removedata'],                             
                             [_('Queue'), 'allow_queue'], 
                             [_('Stop'), 'allow_stop'], 
                             [_('Resume'), 'allow_start'], 
                             [_('Pause'), 'allow_pause'],
                             [_('Super Seed'), 'allow_superseed'],
                             [_('Hash Check'), 'allow_recheck'],
                             [_('Move'), 'allow_move'],
                            ]

        self.perm_checkbox = wx.CheckListBox(self, -1, size = wx.Size(100, 120), style = wx.LB_SINGLE)
        perm_text = [item[0] for item in self.permissions]
        self.perm_checkbox.Set(perm_text)
        permissions_box.Add(self.perm_checkbox, 1, wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, 0)
        outerbox.Add(permissions_box, 0, wx.EXPAND|wx.LEFT|wx.RIGHT, 5)
  
        self.webautostart = wx.CheckBox(self, -1, _('Auto start web service on startup'))
        outerbox.Add(self.webautostart, 0, wx.EXPAND|wx.ALL, 5)
        outerbox.Add(wx.StaticLine(self, -1), 0, wx.GROW|wx.ALL, 3)

        #CheckBox Set Value from Config
        #####################################        

        self.actionbtn = wx.Button(self, -1, "")
        utility.webserver.updateLabels()
        okbtn  = wx.Button(self, wx.ID_OK, _('OK'))
        self.Bind(wx.EVT_BUTTON, self._onOK, okbtn)        
        self.Bind(wx.EVT_CLOSE, self._onClose)
        self.Bind(wx.EVT_BUTTON, self._OnAction, self.actionbtn)

        button_box = wx.BoxSizer(wx.HORIZONTAL)
        button_box.Add(okbtn, 0, wx.ALL, 5)
        button_box.Add(self.actionbtn, 0, wx.ALL, 5)
        outerbox.Add(button_box, 0, wx.ALIGN_CENTER)

        self._loadParams()

        self.SetAutoLayout(True)
        self.SetSizerAndFit(outerbox)

    def _onOK(self, event = None):
        utility.webserver.webdlg = None
        if self._saveParams():
            self.EndModal(wx.ID_OK)
            
    def _onClose(self, event = None):
        utility.webserver.webdlg = None
        if event is not None:
            event.Skip()
            
    def _loadParams(self):
        WebRead = utility.webconfig.Read

        # IP/Port
        host = WebRead('host')
        if host == "":
            default_ip = _('Automatic')
        elif host == "127.0.0.1":
            default_ip = _('Loop Back')
        else:
            default_ip = host
        self.iptext.SetValue(default_ip)
        self.porttext.SetValue(WebRead('port', "int"))
        
        # Auth
        authorization = WebRead('authorization')
        if authorization == "basic":
            self.authorizationtext.SetSelection(0)
        else:
            self.authorizationtext.SetSelection(1)            
        self.username.SetValue(WebRead('username'))
        self.password.SetValue(WebRead('password'))
        self.allowed.SetValue(','.join(WebRead('allowed', "bencode-list")))
        
        # Permissions                    
        for i in range(len(self.permissions)):
            param = self.permissions[i][1]
            checked = WebRead(param, "boolean")
            if checked:
                self.perm_checkbox.Check(i)
        
        # Options
        self.webautostart.SetValue(WebRead('webautostart', "boolean"))

    def _saveParams(self):       
        # IP/Port
        iptext = self.iptext.GetStringSelection()
        if iptext == _('Automatic'):
            host = ""
        elif iptext == _('Loop Back'):
            host = "127.0.0.1"
        else:
            host = iptext
        utility.webconfig.Write('host', host)
        utility.webconfig.Write('port', self.porttext.GetValue())
        
        # Auth
        authorization = self.authorizationtext.GetSelection()
        if authorization == 0:
            utility.webconfig.Write('authorization', "basic")
        else:
            utility.webconfig.Write('authorization', "digest")
        utility.webconfig.Write('username', self.username.GetValue())
        utility.webconfig.Write('password', self.password.GetValue())
        allowed = [ip for ip in self.allowed.GetValue().split(',') if ip.split()]
        utility.webconfig.Write('allowed', allowed, "bencode-list")
        
        # Permissions                    
        for i in range(self.perm_checkbox.GetCount()):
            param = self.permissions[i][1]
            checked = self.perm_checkbox.IsChecked(i)
            utility.webconfig.Write(param, checked, "boolean")
        
        # Options
        utility.webconfig.Write('webautostart', self.webautostart.GetValue(), "boolean")

        utility.webconfig.Flush()
        return True
        
    def _OnAction(self, event = None):
        if not utility.webserver.active:
            if self._saveParams():
                self._startWebService()
        else:
            self._stopWebService()

    def _startWebService(self):
        """
        Start Web Interface Service
        """
        utility.webserver.start()

    def _stopWebService(self):
        """
	Stop Web Service
        """
        utility.webserver.stop()
        
    def updateLabels(self):
        active = utility.webserver.active
        
        if active:
            label = _('Stop')
        else:
            label = _('Start')
        self.actionbtn.SetLabel(label)
        
        self.porttext.Enable(not active)
        self.iptext.Enable(not active)
        self.username.Enable(not active)
        self.password.Enable(not active)
        self.authorizationtext.Enable(not active)
        self.allowed.Enable(not active)

